import { defineStore } from "pinia";
import type { PermissionState, Permission } from "@/typings/permission";
import type { RouteRecordRaw } from "vue-router";
import { store } from "../index";
import type { MenuOption } from "naive-ui";
import { getPermissions } from "@/api/user";
import { setupAfterLoginDynamicRoute } from "@/router/index";
import { genStaticMenu } from "@/router/staticRoutes";

export const usePermissionStore = defineStore("permission", {
  state: (): PermissionState => {
    return {
      permissions: [], //后台返回的所有权限
      accessRoutes: [], //路由列表
      menus: [], //菜单栏列表
    };
  },
  actions: {
    /** 获取权限 */
    async getPermissionTree() {
      const res = await getPermissions();
      this.setPermission(res.data);
      this.setAccessRoutes(res.data);
      this.setMenu(res.data);
      setupAfterLoginDynamicRoute();
    },

    /** 设置所有权限 */
    setPermission(permissions: Permission[]) {
      this.permissions = permissions;
    },

    /** 设置路由 */
    setAccessRoutes(permissions: Permission[]) {
      this.accessRoutes = this.generateRoute(permissions);
    },

    /** 生成路由 */
    generateRoute(permissions: Permission[]) {
      const res: RouteRecordRaw[] = [];

      for (const item of permissions) {
        const routeData: RouteRecordRaw = {
          path: item.path,
          name: item.code,
          redirect: item.redirect,
          meta: {
            icon: item.icon,
            title: item.name,
            translation: item.translation,
            auth: item.auth,
            widgets: item.widgets,
          },
          // @ts-ignore
          component: item.component,
          children: [],
        };
        if (item.children) {
          routeData.children = this.generateRoute(item.children);
        }
        res.push(routeData);
      }

      return res;
    },

    /** 设置菜单 */
    setMenu(permissions: Permission[]) {
      // @ts-ignore
      this.menus = [...genStaticMenu(), ...this.generateMenu(permissions)];
    },

    /** 生成菜单 */
    generateMenu(permissions: Permission[]) {
      const menuList: MenuOption[] = [];
      for (const item of permissions) {
        const menu: MenuOption = {
          translation: item.translation,
          label: item.name,
          show: true,
          key: item.code,
          iconName: item.icon,
        };
        if (item?.children?.length) {
          menu.children = this.generateMenu(item.children);
        }
        menuList.push(menu);
      }

      return menuList;
    },
  },
  persist: true,
});

/** 暴露出去供外部使用 */
export const usePermissionStoreWithout = () => usePermissionStore(store);
